package handlers

import (
	"github.com/gin-gonic/gin"
	"net-linker/models"
	"strconv"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	Offset := (page - 1) * size
	query := models.DB.Model(&models.Article{})
	var count int64
	query.Count(&count)

	var list []models.Article

	err := query.Offset(Offset).Limit(size).Find(&list).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"list":  list,
		},
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var article models.Article
	err := models.DB.Where("id=?", id).First(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": article,
	})
	return
}
func Collection(c *gin.Context) {
	id := c.Query("id")
	var del models.Article
	err := models.DB.Delete(&del, id).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "收藏失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "收藏成功",
	})
	return
}
